package org.comix.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @Creator paladin
 * @Created-date 2009-1-18
 */
public abstract class DateUtil {

	public static final String DEFAULT_FORMAT_STR = "yyyy-MM-dd HH:mm:ss";

	public static final String FULL_FORMAT_STR = "yyyy-MM-dd HH:mm:ss SSS";

	protected static final Map<String, DateFormat> formats = new ConcurrentHashMap<String, DateFormat>();

	protected static DateFormat getFormat(String formatStr) {
		if (formats.get(formatStr) == null) {
			DateFormat f = new SimpleDateFormat(formatStr);
			formats.put(formatStr, f);
		}
		return formats.get(formatStr);
	}

	public static String now() {
		return now(DEFAULT_FORMAT_STR);
	}

	public static Date parse(long time) {
		return new Date(time);
	}

	public static String format(Date date, String formatStr) {
		DateFormat format = getFormat(formatStr);
		return format.format(date);
	}

	public static String now(String formatStr) {
		DateFormat format = getFormat(formatStr);
		return format.format(new Date());
	}

	public static String format(long time, String formatStr) {
		return format(new Date(time), formatStr);
	}

	public static Date parse(String datetime, String formatStr) {
		DateFormat format = getFormat(formatStr);
		try {
			return format.parse(datetime);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

}
